import {
  addHome,
  memberHomeList,
  devicesByFamily,
  deleteHome,
  reqTicket,
  getClientId,
  log,
  getUserInfo,
} from "../../../utils/api/common-api";

import {
  fetch,
  isLogin,
  loginByWx,
  getFamilies,
  changeFamily,
  getCurrentFamily,
} from "@ray-js/wechat";
import { judgeMyApi } from "../../../utils/util/index";
import {
  getRoom,
  getHotel,
  bindTuyaRoom,
  finshBuild,
  getAccessByCompany 
} from "../../../utils/api/common-api";
const requestUrl = new Date().getTime();
Page({
  data: {
    isLogin: false,
    activeNames: [0],
    value: "",
    baseUrl: "plugin://tuya-ap-plugin/auto",
    roomList: [],
    hotel: {},
    uid:requestUrl,
    active:0,
    config:{},
    tenantName: wx.getStorageSync('username'),
    myLogo:'',
    buildRoomInfo:{},
    buildName:'',
    buildPhone:'',
    show: false
  },
  onLoad(options) {},
  onReady() {
  },
  setInfo(){
    const username =  wx.getStorageSync('username')
    log("租户名:", JSON.stringify(username));
    this.setData({tenantName:username})
    getAccessByCompany(username).then(tenantInfo=>{
      const json = tenantInfo.jsonContent
      const config = JSON.parse(json)
      log("租户名信息:", JSON.stringify(tenantInfo));
      log("租户名配置:", JSON.stringify( tenantInfo.jsonContent));
      this.setData({config,myLogo:config.baseUrl + config.wxLogo})
    }).catch(e=>{
      console.log('catch',e)
    })
  },
  /***
   * 进入页面先判断有没有登录，没有的话先登录
   */
  async onShow() {
    const hasLogin = await isLogin();
    this.setData({
      isLogin: hasLogin,
    });
    if (!hasLogin) {
      this.wxLogin();
    }
    const user = await getUserInfo() || 0;
    this.setData({uid:user.uid})
    log("登录用户", JSON.stringify(user), user.uid);

   
  },
  onHide() {},
  onUnload() {},
  onShareAppMessage() {
    return {
      title: "",
    };
  },
  onTabsChange(event) {
    console.log(event.detail)
    if(event.detail === 1){
      this.setInfo()
    }
    // event.detail 的值为当前选中项的索引
    this.setData({ active: event.detail });
  },
  /**
   * 位置列表展开收缩
   * @param {} event
   */
  onCollapseChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  /**
   * 搜索框失去焦点
   * @param {*} e
   */
  blur(e) {
    console.log("场景编码blur：", e.detail);
    this.setData({
      value: e.detail.value,
    });
  },
  /**
   * 搜索框change
   * @param {*} e
   */
  onInputChange(e) {
    console.log("场景编码onChange：", e.detail);
    this.setData({
      value: e.detail,
    });
  },
  /**
   * 人员
   * @param {*} e 
   */
  onBuildNameChange(e) {
    console.log("人员onChange：", e.detail);
    this.setData({
      buildName: e.detail,
    });
  },
  /**
   * 手机号
   * @param {*} e 
   */
  onBuildPhoneChange(e) {
    console.log("手机号onChange：", e.detail);
    this.setData({
      buildPhone: e.detail,
    });
  },
  /**
   * 搜索位置
   * @param {*} event
   * @returns
   */
  async searchRooms(event) {
    /** 调试 begin */
    // this.setData({value: "J21017"});
    log(`搜索场景编码：${this.data.value}`, JSON.stringify(this.data.value), this.data.uid);

    const homeList = await memberHomeList();
    console.log("当前用户小程序创建的家庭", JSON.stringify(homeList), this.data.uid);
    log("当前用户小程序创建的家庭", JSON.stringify(homeList), this.data.uid);
    // homeList.forEach(async (item) => {
    //     try {
    //     const device = await devicesByFamily({
    //       home_id: item.home_id
    //     });
    //     console.log(item.home_id, device);
    //   } catch (error) {
    //     // console.log(error)
    //   }
    // });
    /** 调试 end */

    if (this.data.value === "") {
      wx.showToast({
        title: "请输入场景编码",
        icon: "error",
        duration: 1000,
      });
      return;
    }

    // 获取场景
    const hotelList = await getHotel(this.data.value);
    const hotel = hotelList.list ? hotelList.list[0] : [];
    this.setData({
      hotel,
    });
    log("获取场景:", JSON.stringify(hotel), this.data.uid);
    if (!hotel) {
      wx.showToast({
        title: "找不到场景",
        icon: "error",
        duration: 1000,
      });
      return;
    }

    // 优化，把没有完成的默认放上面
    // 排序： 未完成，位置，位置
    // 获取位置
    const getRoomList = await getRoom(this.data.value);
    const roomList = getRoomList ? getRoomList : [];
    log("获取位置:", JSON.stringify(roomList), this.data.uid);
    this.setData({
      roomList,
    });
  },
  /**
   * 点击联网按钮-联网插件
   * @param {*} param0
   */
  async devicNetworking({ currentTarget }) {
    wx.showToast({
      title: "请稍等...",
      icon: "error",
      duration: 3000,
    });
    let homeId = "";
    const {
      dataset: { baseurl, room },
    } = currentTarget;

    // 获取 封装好的 ticket，clientId
    const [{ ticket }, clientId] = await Promise.all([
      reqTicket(),
      getClientId(),
    ]);

    // 与saas没有建立关联
    // 直接创建，sass把上一个删除
    // if (!room.homeId) {
    // {
    //   "spaceNo":"507位置",
    //   "homeId":"111" //涂鸦家庭号
    //   "hotelCode":"S33" //场景编码
    //   "deviceList":["sfsaf","fasfsas"]
    //   }
    const {
      hotelCode,
      hotelName,
      company,
      brand,
      address,
      provinceCode,
      cityCode,
      regionCode,
      province,
      city,
      region,
    } = this.data.hotel;
    const home = {
      name: `${hotelCode}-${room.spaceNo}`,
      geo_name: `${provinceCode},${cityCode},${regionCode},${province},${city},${region}`, // room.spaceNo
      lat: 0,
      lon: 0,
    };
    // 将上面的信息添加到小程序的家庭里
    try {
      log("小程序addHome参数", JSON.stringify(home), this.data.uid);
      homeId = await addHome(home) || '';
      log(`小程序addHomeId: ${homeId}`, JSON.stringify(homeId), this.data.uid);
    } catch (error) {
      log("小程序增加位置异常", JSON.stringify(error), this.data.uid);
    }

    if(!homeId) {
      log("小程序增加位置异常", "创建的homeId为空", this.data.uid);
      wx.showModal({
        showCancel: false,
        content:"抱歉，配网遇到了点小问题，请反馈视频或截图给我们！",
        success:()=>{
          log("小程序增加位置异常", JSON.stringify(JSON.stringify({
            hotelCode,
            spaceNo: room.spaceNo,
            homeId,
          }),), '用户反馈异常');
        }
      })
      return
    }

    // 上报saas hotelCode , spaceNo, homeId
    log(
      `上报saas:[hotelCode:${hotelCode},spaceNo:${room.spaceNo},homeId:${homeId}]`,
      JSON.stringify({
        hotelCode,
        spaceNo: room.spaceNo,
        homeId,
      }),
      this.data.uid
    );
    // 将小程序家庭号绑定saas的位置号
    const res = await bindTuyaRoom({
      hotelCode,
      spaceNo: room.spaceNo,
      homeId,
    });
    log("上报saas绑定HomeID返回:", JSON.stringify(res), this.data.uid);
    // } else {
    //   homeId = room.homeId;
    // }
    // 进行配网操作
    log(
      "进行配网操作devicNetworking",
      JSON.stringify({ baseurl, clientId, ticket, homeId }),
      this.data.uid
    );

    wx.navigateTo({
      url: `${baseurl}?ticket=${ticket}&clientId=${clientId}&gid=${homeId}&self_env=inner`,
    });
  },
  
  /**
   * 点击设备信息-面板插件
   * @param {*} param0
   */
  async getDeciveInfo({ currentTarget }) {
    wx.showToast({
      title: "请稍等...",
      icon: "error",
      duration: 3000,
    });

    const {
      dataset: { baseurl, room },
    } = currentTarget;

    // 获取 封装好的 ticket，clientId
    const [{ ticket }, clientId] = await Promise.all([
      reqTicket(),
      getClientId(),
    ]);

    console.log('room:',room)
    const { deviceList,buildName } = room
    const device_id = deviceList[0]
    
    log(
      "进行面板操作devicNetworking",
      JSON.stringify({ baseurl, ticket, clientId, device_id }),
      this.data.uid
    );

    const name = buildName
    wx.navigateTo({
      url: `/packageA/home_center/common_panel/index?device_id=${device_id}&device_name=${name}`,
    })

    // wx.navigateTo({
    //   url: `plugin://tuya-panel-plugin/panel?ticket=${ticket}&clientId=${clientId}&device_id=${device_id}`,
    // });
  },
  /**
   * 上报施工完成
   * @param {*} param0
   */
  async reportCompate() {
    console.log(this.data.buildRoomInfo)
    console.log(this.data.buildName)
    console.log(this.data.buildPhone)
    // hotelCode , spaceNo, homeInfo
    const { hotelCode, spaceNo } = this.data.buildRoomInfo;
    const buildName = this.data.buildName
    const buildPhone = this.data.buildPhone
    const session_info = wx.getStorageSync('session_info')
    log("上报施工完成reportCompate:", JSON.stringify(this.data.buildRoomInfo), session_info.uid);
    log("上报施工完成 wxUid:", session_info.uid, session_info.uid);
    const res = await finshBuild({
      hotelCode,
      spaceNo,
      buildPhone,
      buildName,
      wxUid:session_info.uid
    });
    if (res) {
      this.onClose()
      this.searchRooms();
    }
  },
  /**
   * 封装好的微信登录
   * @returns
   */
  wxLogin: async function () {
    let canIuse = await judgeMyApi({
      myApi: "getUserProfile",
      myVersion: "2.24.0",
    });
    console.log("canIuse微信环境接口", canIuse);
    log("canIuse微信环境接口:", JSON.stringify(canIuse), this.data.uid);
    if (!canIuse) return false;
    wx.showLoading({
      title: "正在登陆",
    });
    try {
      await loginByWx();
      wx.showToast({
        title: "登录成功",
        duration: 1000,
      });
      this.setData({
        isLogin: true,
      });
    } catch (error) {
      console.log(error);
      log("微信登陆失败:", JSON.stringify(error), this.data.uid);
      wx.showToast({
        title: "登录失败",
        icon: "error",
        duration: 1000,
      });
    } finally {
      wx.hideLoading();
    }
  },
  gotoDemo() {
    wx.navigateTo({
      url: `/pages/guide/index`,
    });
  },
  showPopup({ currentTarget }) {
    console.log(currentTarget)
    const { room } = currentTarget.dataset;
    this.setData({ show: true});
    this.setData({buildRoomInfo: room});
  },
  onClose() {
    this.setData({ show: false });
  },
  tenantLoginOut(){
    wx.clearStorage('userInfo')
    wx.redirectTo({
      url: `/pages/login/index`,
    })
  }
});
